<script setup>
import { ref } from 'vue'
import { userUpdatePasswordService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const formRef = ref()
const pwdForm = ref({
  password: '',
  newPassword: '',
  userName: ''
})

const checkSameAsNewPwd = (rule, value, callback) => {
  // 校验确认密码必须和新密码一样
  if (value === pwdForm.value.Password) {
    callback(new Error('新密码必须和旧密码不一样'))
  } else {
    callback()
  }
}
const rules = ref({
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 1, max: 15, message: '长度在1-15位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 15, message: '密码长度在1-15位之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 1, max: 15, message: '密码长度在1-15位之间', trigger: 'blur' },
    { validator: checkSameAsNewPwd, trigger: 'blur' }
  ]
})

const userStore = useUserStore()
const router = useRouter()

const submitForm = async () => {
  await formRef.value.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success('密码修改成功')

  // 密码修改成功后，退出重新登录
  // 清空本地存储的 token 和 个人信息
  userStore.setToken('')
  userStore.setUser({})

  // 拦截登录
  router.push('/login')
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="修改密码" class="container">
    <el-form
      ref="formRef"
      :model="pwdForm"
      label-position="left"
      :rules="rules"
      label-width="90px"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="pwdForm.userName" class="input"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="pwdForm.password"
          show-password
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="pwdForm.newPassword"
          show-password
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="50px">
        <el-button type="primary" @click="submitForm" class="select-button"
          >修改密码</el-button
        >
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
<style lang="scss" scoped>
.container {
  border-radius: 20px;
  font-weight: bold;
  font-size: 17px;
}
.select-button {
  background-color: #077aee;
  color: #fff;
}
.input {
  width: 150px;
}
</style>
